package com.objectdraw.client.objectdraw;
import java.awt.*;
import java.awt.event.*;

/**
 * controls mouse events for drawing freehand drawings
 * @author jgulik, cfruehan
 *
 */
public class FreehandTool implements Tool {

	protected DrawingCanvas canvas;
	protected Point startingMousePosition;

	/**
	 * instantiates the tool
	 * 
	 * @param canvas the canvas upon which this tool acts
	 */
	public FreehandTool(DrawingCanvas canvas) {
		this.canvas = canvas;
	}

	/**
	 * original implementation of drawing line segments for freehand objects. 
	 * 
	 * @param p1 starting point of line
	 * @param p2 ending point of line
	 */
	protected void drawLineSegment(Point p1, Point p2) {
		canvas.getImageBufferGraphics().drawLine(p1.x,p1.y,
				p2.x, p2.y);
		/* redraw only the small rectangle  */
		/* containing the new line segment  */
		int x0 = Math.min(p1.x, p2.x);
		int y0 = Math.min(p1.y, p2.y);
		int dx = Math.abs(p2.x - p1.x)+ 1;
		int dy = Math.abs(p2.y - p1.y) + 1;
		canvas.repaint(x0, y0, dx, dy);
	}
	
	protected FreehandDrawingObject myfdo;
	
	/**
	 * takes position of mouse event and starts a new freehanddrawingobjec
	 */
	public void mousePressed(MouseEvent e)  {
		/* Establish starting point for next drawing */
		startingMousePosition = e.getPoint();
		myfdo=new FreehandDrawingObject(e.getPoint(),canvas.penColor);
		IDrawingObjectLink myfdoLink=new IDrawingObjectLink(myfdo);
		myfdoLink.next=canvas.firstObject;
		canvas.push(myfdoLink);
	}

	/**
	 * adds position of mouse event to current freehanddrawingobject
	 */
	public void mouseDragged(MouseEvent e)  {
		Point newMousePosition = e.getPoint();
		myfdo.add(newMousePosition);
		drawLineSegment(startingMousePosition,newMousePosition);
		/* update current mouse coordinates */
		startingMousePosition = newMousePosition;
		if(e.getWhen() != 0){
			canvas.com.sendMessage("mouse dragged "+e.getPoint().x+" "+e.getPoint().y);
		}
	}

	/*null methods*/

	/**
	 * unimplemented
	 */
	public void mouseReleased(MouseEvent e) {

	}
}
